<?php

namespace App\Http\Controllers\Home;

use App\Http\Servers\Home\BaseServer;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class SeoController extends CommonController
{
    //rss
    public function rss(Request $request, BaseServer $baseServer)
    {
        $data['url'] = $baseServer->getUrl();

        $data['title'] = config('set.web_title');

        $data['description'] = config('set.web_description');

        $data['link'] = config('set.web_url');

        $data['generator'] = config('app.generator_name');

        return response()->view('home.pc.seo.rss', $data)->header('Content-Type', 'text/xml');
    }

    //网站地图
    public function sitemap(Request $request, BaseServer $baseServer)
    {
        $data['url'] = $baseServer->getUrl(true);

        $data['title'] = config('app.sitemap_name') . '_' . config('set.web_name');

        $data['keywords'] = config('set.web_keywords');
        $baseServer->keywordDowork($request, $data['keywords']);

        $data['description'] = config('set.web_description');

        $data['frames'] = $baseServer->frame([
            ['url' => '', 'name' => config('app.sitemap_name')],
        ]);

        return view('home.pc.seo.sitemap', $data);

    }

    //主动推送
    public function pushurl(Request $request, BaseServer $baseServer)
    {
        if (empty(config('set.push_token'))) {
            $message['message'] = message(false, '推送失败', '未设置百度推送token,请前往后台添加!');
            return back()->with($message);
        }
        $urls = array_column($baseServer->getUrl(), 'url');
        $urlsArray = array_chunk($urls, 2000);
        $api = 'http://data.zz.baidu.com/urls?site=' . explode('//', config('set.web_url'))[1] . '&token=' . config('set.push_token');
//        $urls = ['http://demo.tuicco.cn/test1.html', 'http://demo.tuicco.cn/test2.html'];
//        $api = 'http://data.zz.baidu.com/urls?site=demo.tuicco.cn&token=BVYDeVwDikKkjoec';
        $ch = curl_init();
        $postStatus = true;
        foreach ($urlsArray as $chunk) {
            $options = array(
                CURLOPT_URL => $api,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => implode("\n", $chunk),
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
            );
            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);
            $status = json_decode($result, true);
            if (empty($status['remain'])) {
                $postStatus = false;
            }
        }
        if ($postStatus) {
            $message['message'] = message(true, config('app.push_success_name'), config('app.push_success_explore_name'));
        } else {
            $message['message'] = message(false, config('app.push_false_name'), config('app.push_false_explore_name'));
        }
        return back()->with($message);
    }
}
